package arrays;

import java.util.Arrays;

public class MyArrayList {
    public int[] elem;
    public int usedSize;
    public static int capacity=10;
    public MyArrayList(){
        this.elem=new int[capacity];
    }
    public boolean isFull() {
        return this.usedSize==capacity;
    }
    public void add(int pos, int data) {
        if (pos<0||pos>this.usedSize){
            System.out.println("pos的位置不合法");
            return;
        }
        if(isFull()){
            this.elem= Arrays.copyOf(this.elem,capacity*2);
            capacity*=2;
        }
        for (int i = this.usedSize-1; i >=pos; i--) {
            this.elem[i+1]=this.elem[i];
        }
        this.elem[pos]=data;
        this.usedSize++;
    }
    public void display() {
        for (int num:this.elem) {
            System.out.print(num+" ");
        }
        System.out.println();
    }
    public boolean isEmpty() {
        return this.usedSize==0;
    }
    public boolean contains(int toFind) {
        if(isEmpty()){
            return false;
        }
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i]==toFind){
                return true;
            }
        }
        return false;
    }
    public int search(int toFind) {
        if (isEmpty()){
            return -1;
        }
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i]==toFind){
                return i;
            }
        }
        return -1;
    }
    public int getPos(int pos) {
        if (isEmpty()){
            throw new RuntimeException("顺序表是空的");
        }
        if (pos<0||pos>=this.usedSize){
            throw new RuntimeException("pos不合法");
        }
        return this.elem[pos];
    }
    public int size() {
        return this.usedSize;
    }
    public void setPos(int pos, int value) {
        if (isEmpty()){
            throw new RuntimeException("顺序表是空的");
        }
        if (pos<0||pos>=this.usedSize){
            throw new RuntimeException("pos不合法");
        }
        this.elem[pos]=value;
    }
    public void remove(int toRemove) {
        if (isEmpty()){
            return;
        }
        int index=search(toRemove);
        for (int i = index; i < this.usedSize-1; i++) {
            this.elem[i]=this.elem[i+1];
        }
        this.usedSize--;
    }
    public void clear() {
        for (int i = 0; i < this.usedSize; i++) {
            this.elem[i]=0;
        }
        this.usedSize=0;
    }
}
